package com.kate.order.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author 新梦想.陈超
 * @version 2021.2
 * @Description: {TODO}
 * @date 2023/7/10 上午9:01
 */

public class SqlSessionUtil {
    private static InputStream inputStream;
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
    private static SqlSessionFactory sqlSessionFactory;

    static {//静态块----在类加载时，先执行并只会执行一次
        String resource = "mybatis-config.xml";
        try {
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //TODO  1.获取sqlSession
    public static SqlSession init() throws IOException {
        //将sqlSession放入到
        if (threadLocal.get() == null) {
            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            threadLocal.set(sqlSession);
        }
        return threadLocal.get();
    }
    //TODO 2.释放资源方法
    public static void destroy() throws IOException {
        if (threadLocal.get() != null) {
            threadLocal.get().close();
            threadLocal.remove();//避免内存泄漏
        }
        inputStream.close();
    }

}
